package com.liuyucheng.tools.autotimer;

import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * 自动更新系统时间
 *
 * @author LiuYuCheng
 * @date 2023年06月09日 10:06
 */
public class UpdateLocalTimeUtil {

    public static void main(String[] args) {

    }

    /**
     * 同步系统时间为互联网时间
     */
    public static String synchronizeTime(){
        URL url;
        String day = null;
        String hour = null;
        try {
            //通过url连接拿到网络当前时间
            url = new URL("https://www.baidu.com/");
            URLConnection connection = url.openConnection();
            connection.connect();
            long ld = connection.getDate();
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(ld);

            DateFormat dayFormatter = new SimpleDateFormat("yyyy-MM-dd");
            DateFormat hourFormatter = new SimpleDateFormat("HH:mm:ss");

            day = dayFormatter.format(calendar.getTime());
            hour = hourFormatter.format(calendar.getTime());
            String name = System.getProperty("os.name");
            if (name.contains("Windows")) {
                String cmd = " cmd /c date " + day;
                Runtime.getRuntime().exec(cmd);
                cmd = " cmd /c time " + hour;
                Runtime.getRuntime().exec(cmd);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return day + hour;
    }
}
